package com.joinpay.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.joinpay.dao.BaseDao;
import com.joinpay.dao.GroupDao;
import com.joinpay.dao.UserDao;
import com.joinpay.model.Group;
import com.joinpay.model.User;
import com.joinpay.service.GroupService;
import com.joinpay.util.ManageTimeUtil;

@Service
public class GroupServiceImpl implements GroupService {

	@Resource
	private GroupDao groupDao;
	@Resource
	private UserDao userDao;

	@Override
	@Transactional
	public List<Group> getGroupList(Map map) {
		// TODO Auto-generated method stub
		return groupDao.selectParam(map);
	}

	@Override
	@Transactional
	public int addGroup(String username,String uID, String groupName) {
		// TODO Auto-generated method stub
		String currentTime = ManageTimeUtil.getCurrentTime();
		Group group = new Group();
		group.setuID(uID);
		group.setGroupName(groupName);
		group.setCreateUser(username);
		group.setCreateTime(currentTime);
		group.setModifyUser(username);
		group.setModifyTime(currentTime);
		return groupDao.insert(group);
	}

	@Override
	@Transactional
	public int updateGroup(String username,String id, String groupName) {
		// TODO Auto-generated method stub
		String currentTime = ManageTimeUtil.getCurrentTime();
		Group group = new Group();
		group.setId(id);
		group.setGroupName(groupName);
		group.setModifyUser(username);
		group.setModifyTime(currentTime);
		System.out.println(username+"<---->"+currentTime);
		return groupDao.update(group);
	}

	@Override
	@Transactional
	public int deleteGroup(String id) {
		// TODO Auto-generated methods
			Map<String, String> map = new HashMap<String, String>();
			map.put("uID", id);
			List<Group> groupList = groupDao.selectParam(map);
			groupDao.deletePK(id);
			if (groupList.size() > 0) {
				for (int i = 0; i < groupList.size(); i++) {
					deleteGroup(groupList.get(i).getId());
				}
				return 1;
			} else {
				map.put("departID", id);
				List<User> userList = userDao.selectParam(map);
				for (int i = 0; i < userList.size(); i++) {
					userList.get(i).setDepartID("0");
					userList.get(i).setDepartName(" ");
					userDao.update(userList.get(i));
				}
				return 1;
			}
			// TODO: handle exception
	}

	@Override
	public String getCompleteGroup(String id) {
		// TODO Auto-generated method stub
		String groupName =null;
		Map<String,String> map = new HashMap<String,String>();
		map.put("id", id);
		List<Group> groupList = groupDao.selectParam(map);
		groupName = groupList.get(0).getGroupName();
		if(groupList.get(0).getuID().equals("rootbranch")){
			return groupName;
		}else{
			return getCompleteGroup(groupList.get(0).getuID())+"-"+groupName;
		}
	}
}
